﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SAPbouiCOM;

namespace BoAddonBiz_FreightForwarder.Approval
{
    class B1Form_ApprovalStep : SAPBoAddon.B1Form
    {
        #region override
        protected override bool BeforeSaveCheckFormData()
        {
            return true;
        }

        protected override void FormEditModeChange(SAPBoAddon.frmItemEditMode frmEditMode)
        {

        }

        protected override void FormInfoSetting(SAPBoAddon.B1FormSetting FormSetting)
        {
            this.FormSetting.FormType = B1FormTypes.ado_AVA_FF_ApprovalStep;
            this.FormSetting.FormFileName = "AVA_ApprovalStepForm.srf";

            FormSetting.AutoGetObjectNextNumber = true;
            #region 控件是否可编辑
            FormSetting.FormModeSetting.StatusItemUID = "39";
            SAPBoAddon.BrowseModeSetting ModeSetting;
            ModeSetting = FormSetting.FormModeSetting.BrowseModeSettingList.Add();
            ModeSetting.Status = "C";
            ModeSetting.itmBrowseModeDisable = new string[] { "40", "41", "27", "29" };
            #endregion
        }

        protected override void InitializeForm(SAPBoAddon.B1FormInitializePar InitPar)
        {
            throw new NotImplementedException();
        }
        #endregion
        #region constraction
        public B1Form_ApprovalStep()
        {
            this.frm_FormDataEvent += new SAPBoAddon.IB1FormEvents.B1FormDataEventEventHandler(B1Form_ApprovalMessage_frm_FormDataEvent);
            this.frm_ItemEvent += new SAPBoAddon.IB1FormEvents.B1ItemEventEventHandler(B1Form_ApprovalStep_frm_ItemEvent);
        }
        #endregion
        #region events
        void B1Form_ApprovalMessage_frm_FormDataEvent(SAPBoAddon.B1AddonBase.B1BusinessObjectInfo pVal, ref bool BubbleEvent)
        {
            try
            {
                if (pVal.BeforeAction == false)
                {
                    if (pVal.ActionSuccess)
                    {
                        if (pVal.EventType == SAPbouiCOM.BoEventTypes.et_FORM_DATA_ADD)
                        {
                            //审批请求
                            Request(pVal.FormUID);
                        }
                        if (pVal.EventType == BoEventTypes.et_FORM_DATA_UPDATE)
                        {
                            #region 审批答复
                            Reply();
                            #endregion
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }
        void B1Form_ApprovalStep_frm_ItemEvent(SAPBoAddon.B1AddonBase.B1ItemEvent pVal, ref bool BubbleEvent)
        {
            if (pVal.BeforeAction)
            {
                if (pVal.ItemUID == "1" && pVal.EventType == BoEventTypes.et_ITEM_PRESSED)
                {
                    SaveBeforeCheck(pVal.FormUID, ref BubbleEvent);
                }
            }
            else
            {
                if (pVal.ItemUID == "Link_1" && pVal.EventType == BoEventTypes.et_ITEM_PRESSED)
                {
                    SAPbouiCOM.DBDataSource dbds = CurrentForm.DataSources.DBDataSources.Item("@AVA_OWDD");
                    //Utils.OpenUserDeFinedObjectForm(this.CurrentForm, pVal.ItemUID, dbds.GetValue("U_OrderType", dbds.Offset).Trim());
                    Utils.OpenUserDeFinedObjectForm(this.CurrentForm, pVal.ItemUID, dbds.GetValue("U_OrderType", dbds.Offset).Trim(),this.ShowForm);
                }
                if (pVal.ItemUID == "Link_2" && pVal.EventType == BoEventTypes.et_ITEM_PRESSED)
                {
                    Utils.OpenUserDeFinedObjectForm(this.CurrentForm, pVal.ItemUID, "AVA_ApprovalTem");
                }
            }
        }
        #endregion
        #region methods
        /// <summary>
        /// 保存之前检查Code、Name
        /// </summary>
        /// <param name="FormUID"></param>
        /// <param name="BubbleEvent"></param>
        private void SaveBeforeCheck(string FormUID, ref bool BubbleEvent)
        {
            SAPbouiCOM.Form oForm;
            SAPbouiCOM.DBDataSource dbds;
            //SAPbouiCOM.DBDataSource dbds2;

            oForm = SBOApp.Forms.Item(FormUID);
            dbds = oForm.DataSources.DBDataSources.Item("@AVA_OWDD");
            if (oForm.Mode != BoFormMode.fm_ADD_MODE && oForm.Mode != BoFormMode.fm_UPDATE_MODE && oForm.Mode != BoFormMode.fm_EDIT_MODE) return;

            dbds.SetValue("Code", dbds.Offset, dbds.GetValue("DocEntry", dbds.Offset).Trim());
            dbds.SetValue("Name", dbds.Offset, dbds.GetValue("DocEntry", dbds.Offset).Trim());

            //dbds2 = oForm.DataSources.DBDataSources.Item("@AVA_WDD1");
            //dbds2.SetValue("U_WstCode", dbds2.Size - 1, dbds.GetValue("U_WstCode", dbds.Offset).Trim());
            //dbds2.SetValue("U_UserID", dbds2.Size - 1, "");
            //dbds2.SetValue("U_Response", dbds2.Size - 1, "");
            //dbds2.SetValue("U_ResponseDate", dbds2.Size - 1, "");
            //dbds2.SetValue("U_ResponseTime", dbds2.Size - 1, "");

        }
        /// <summary>
        /// 发送内部信息
        /// </summary>
        /// <param name="Subject"></param>
        /// <param name="MessageText"></param>
        /// <param name="UserCode"></param>
        /// <param name="Object"></param>
        /// <param name="DocEntry"></param>
        private void SendMessage(string Subject, string MessageText, string UserCode, string DocEntry = null)
        {
            int errCode;
            string errMsg;
            SAPbobsCOM.Messages oMsgs;
            oMsgs = SBOCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oMessages);

            oMsgs.Subject = Subject;
            oMsgs.MessageText = MessageText;
            oMsgs.Priority = SAPbobsCOM.BoMsgPriorities.pr_High;//优先级别           

            #region 收件人配置
            oMsgs.Recipients.Add();
            oMsgs.Recipients.UserCode = UserCode;
            oMsgs.Recipients.SendInternal = SAPbobsCOM.BoYesNoEnum.tYES;
            #endregion
            #region 信息内容
            if (!string.IsNullOrEmpty(DocEntry))
            {
                oMsgs.AddDataColumn("单据编码", DocEntry, SAPbobsCOM.BoObjectTypes.oMessages, DocEntry);
            }
            #endregion
            if (oMsgs.Add() != 0)
            {
                SBOCompany.GetLastError(out errCode, out errMsg);
                throw (new Exception("发送系统信息错误：" + errMsg));
            }
        }
        /// <summary>
        /// 审批答复
        /// </summary>
        private void Reply()
        {
            try
            {
                SAPbouiCOM.Form oForm = CurrentForm;
                SAPbouiCOM.DBDataSource dbds = oForm.DataSources.DBDataSources.Item("@AVA_OWDD");
                string SQL;
                string OrderName = string.Empty;
                string UserCode = string.Empty;
                string OrderEntry = string.Empty;
                string SerialNumber = string.Empty;
                string Response = string.Empty;
                SAPbobsCOM.Recordset ors = SBOCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);
                if (SBOCompany.InTransaction == false) SBOCompany.StartTransaction();
                string Status = dbds.GetValue("U_AppStatus", dbds.Offset).Trim();
                switch (Status)
                {
                    case "2":
                        ors.DoQuery("select TableName,Name from OUDO  where Code = '" + dbds.GetValue("U_OrderType", dbds.Offset).Trim() + "'");
                        OrderName = ors.Fields.Item("Name").Value;
                        SQL = "UPDATE [@" + ors.Fields.Item("TableName").Value.ToString().Trim() + "] SET U_Status = 'R',U_Appraiser='" + SBOCompany.UserSignature.ToString() + "' Where DocEntry = " + dbds.GetValue("U_DocEntry", dbds.Offset).Trim() + "";
                        ors.DoQuery(SQL);
                        ors.DoQuery("SELECT User_Code FROM OUSR Where UserID = " + dbds.GetValue("U_OwnerID", dbds.Offset).Trim());
                        UserCode = ors.Fields.Item("User_Code").Value;
                        OrderEntry = dbds.GetValue("U_DocEntry", dbds.Offset).Trim();
                        SerialNumber = dbds.GetValue("U_SerialNum", dbds.Offset).Trim();
                        Response = dbds.GetValue("U_Response", dbds.Offset).Trim();
                        #region 写入审批信息
                        SQL = @"UPDATE T1 SET T1.U_WstCode = '{0}',T1.U_UserID = '{1}',T1.U_Response = '{2}',T1.U_ResponseDate = '{3}',T1.U_ResponseTime = '{4}'
                                FROM [@AVA_OWDD] T0
	                                INNER JOIN [@AVA_WDD1] T1 ON T0.Code = T1.Code And T1.LineId = (SELECT MAX(LineId) LineId FROM [@AVA_WDD1] Where Code = T0.Code)
                                Where T0.DocEntry = '{5}'";
                        ors.DoQuery(string.Format(SQL, dbds.GetValue("U_WstCode", dbds.Offset).Trim(), SBOCompany.UserSignature.ToString(), dbds.GetValue("U_Response", dbds.Offset).Trim(), DateTime.Now.ToShortDateString(), DateTime.Now.ToString("HHmm"), dbds.GetValue("DocEntry", dbds.Offset).Trim()));
                        #endregion
                        SendMessage("审批通过", OrderName + " 单据编号：" + OrderEntry + " 流水号：" + SerialNumber + " 审核通过。\r\n" + Response, UserCode);
                        #region 下级审批

                        #endregion
                        break;
                    case "1":
                        ors.DoQuery("select TableName,Name from OUDO  where Code = '" + dbds.GetValue("U_OrderType", dbds.Offset).Trim() + "'");
                        OrderName = ors.Fields.Item("Name").Value;
                        SQL = "UPDATE [@" + ors.Fields.Item("TableName").Value.ToString().Trim() + "] SET U_Status = 'P',U_Appraiser='" + SBOCompany.UserSignature.ToString() + "' Where DocEntry = " + dbds.GetValue("U_DocEntry", dbds.Offset).Trim() + "";
                        ors.DoQuery(SQL);
                        ors.DoQuery("SELECT User_Code FROM OUSR Where UserID = " + dbds.GetValue("U_OwnerID", dbds.Offset).Trim());
                        UserCode = ors.Fields.Item("User_Code").Value;
                        OrderEntry = dbds.GetValue("U_DocEntry", dbds.Offset).Trim();
                        SerialNumber = dbds.GetValue("U_SerialNum", dbds.Offset).Trim();
                        Response = dbds.GetValue("U_Response", dbds.Offset).Trim();
                        #region 写入审批信息
                        SQL = @"UPDATE T1 SET T1.U_WstCode = '{0}',T1.U_UserID = '{1}',T1.U_Response = '{2}',T1.U_ResponseDate = '{3}',T1.U_ResponseTime = '{4}'
                                FROM [@AVA_OWDD] T0
	                                INNER JOIN [@AVA_WDD1] T1 ON T0.Code = T1.Code And T1.LineId = (SELECT MAX(LineId) LineId FROM [@AVA_WDD1] Where Code = T0.Code)
                                Where T0.DocEntry = '{5}'";
                        ors.DoQuery(string.Format(SQL, dbds.GetValue("U_WstCode", dbds.Offset).Trim(), SBOCompany.UserSignature.ToString(), dbds.GetValue("U_Response", dbds.Offset).Trim(), DateTime.Now.ToShortDateString(), DateTime.Now.ToString("HHmm"), dbds.GetValue("DocEntry", dbds.Offset).Trim()));
                        #endregion
                        SendMessage("审批未通过", OrderName + " 单据编号：" + OrderEntry + " 流水号：" + SerialNumber + " 审核未通过。\r\n原因：\r\n" + Response, UserCode);
                        break;
                }
                ors.DoQuery("UPDATE [@AVA_OWDD] SET U_Status='C' Where DocEntry = '" + dbds.GetValue("DocEntry", dbds.Offset).Trim() + "'");


                if (SBOCompany.InTransaction) SBOCompany.EndTransaction(SAPbobsCOM.BoWfTransOpt.wf_Commit);
            }
            catch (Exception ex)
            {
                if (SBOCompany.InTransaction) SBOCompany.EndTransaction(SAPbobsCOM.BoWfTransOpt.wf_RollBack);
                throw (ex);
            }
        }
        /// <summary>
        /// 审批请求
        /// </summary>
        private void Request(string FormUID)
        {
            #region 发送审批信息
            SAPbouiCOM.Form oForm = SBOApp.Forms.Item(FormUID); ;
            SAPbouiCOM.Form oParentForm = SBOApp.Forms.Item(oForm.DataSources.UserDataSources.Item("ParentUID").Value);
            SAPbouiCOM.DBDataSource dbds = oForm.DataSources.DBDataSources.Item("@AVA_OWDD");
            SAPbobsCOM.Recordset ors = SBOCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);
            string DocEntry = string.Empty;
            string Enquire = string.Empty;
            string UserCode = string.Empty;
            string BaseEntry = string.Empty;
            DocEntry = dbds.GetValue("DocEntry", dbds.Offset).Trim();
            Enquire = dbds.GetValue("U_Enquire", dbds.Offset).Trim();//审批描述

            string SQL = @"SELECT T0.U_WtmCode,T0.U_WstCode,T6.USER_CODE
                                                FROM [@AVA_OWDD] T0
	                                                INNER JOIN [@AVA_OWTM] T1 ON T0.U_WtmCode = T1.U_AppCode
	                                                INNER JOIN [@AVA_WTM2] T2 ON T1.Code = T2.Code And T0.U_WstCode = T2.U_WstCode
	                                                INNER JOIN [@AVA_OWST] T3 ON T2.U_WstCode = T3.U_AppCode
	                                                INNER JOIN [@AVA_WST1] T4 ON T3.Code = T4.Code
	                                                LEFT JOIN [@AVA_WDD1] T5 ON T0.Code = T5.Code And T4.U_UserID <> T5.U_UserID
	                                                INNER JOIN [OUSR] T6 ON T4.U_UserID = T6.USERID
                                                Where T0.DocEntry = '{0}'";
            ors.DoQuery(string.Format(SQL, DocEntry));
            if (ors.RecordCount > 0)
            {
                for (int i = 0; i < ors.RecordCount; i++)
                {
                    UserCode = ors.Fields.Item("USER_CODE").Value.ToString();
                    //发送信息                        
                    SendMessage("单据审批", Enquire, UserCode, DocEntry);
                    ors.MoveNext();
                }
            }
            //更新单据状态
            ors.DoQuery("select TableName from [OUDO] where Code = '" + dbds.GetValue("U_OrderType", dbds.Offset).Trim() + "'");
            BaseEntry = dbds.GetValue("U_DocEntry", dbds.Offset).Trim();
            SQL = "UPDATE [@" + ors.Fields.Item("TableName").Value.ToString().Trim() + "] SET U_Status = 'A' Where DocEntry = " + BaseEntry;
            ors.DoQuery(SQL);
            //oForm.Items.Item("2").Click(BoCellClickType.ct_Collapsed);
            //oParentForm.Select();
            //oParentForm.Mode = BoFormMode.fm_FIND_MODE;
            //SAPBoAddon.B1Assistant.Item.SetEnabled(oParentForm, "3", true);
            //SAPBoAddon.B1Assistant.Item.SetValue(oParentForm, "7", "A");
            //oForm.Close();
            //oParentForm.Items.Item("1").Click(BoCellClickType.ct_Collapsed);
            SBOApp.StatusBar.SetText("审批信息已发送到" + UserCode, BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Success);
            #endregion
        }
        #endregion
    }
}
